package cn.wolfcode.web.interceptor;

import cn.wolfcode.ssm.domain.Employee;
import cn.wolfcode.ssm.service.IPermissionService;
import cn.wolfcode.ssm.util.UserContext;
import cn.wolfcode.ssm.util.requiredPermission;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

public class PermissionInterceptor implements HandlerInterceptor {


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 1. 获取当前登陆用户
        // Employee employee = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        Employee employee = UserContext.getCurrentUser();
        // 2.判断是否为超管
        if (employee.isAdmin()) {
            // 是超管就放行
            return true;
        }
        // 3. 不是就获取controller具体要执行的方法(这一步需要强转)
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 4. 拿到贴有自定义注解的方法
        requiredPermission annotation = handlerMethod.getMethodAnnotation(requiredPermission.class);
        // 4.1 判断方法上是否贴了自定义注解
        if (annotation == null){
            // 没贴就放行
            return true;
        }
        // 5. 获取该用户的权限表达式
        String expression = annotation.expression();
        // 6. 获取当前用户所有有的权限集合
        // List<String> permissions = (List<String>)request.getSession().getAttribute("PERMISSION_IN_SESSION");
        List<String> permissions = UserContext.getPermissions();
        // 7. 看当前用户的权限是否包含在权限表达式集合中
        // 7.1 如果包含就放行
        if (permissions.contains(expression)){
            return true;
        }
        // 8. 不在就跳转到指定页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        // 9. 不放行
        return false;
    }
}

